package com.kredit.kotlin.firebase

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.text.TextUtils
import android.util.Log
import com.flashcash.solu.R
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.view.SplashActivity
import com.flashcash.solu.widget.XLeoSp
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class SimpleFirebaseMessagingService : FirebaseMessagingService() {

    companion object {
        const val TAG = "FirebaseMsgService"
        const val SP_FIREBASE_TOKEN = "shared_preference_firebase_token"
        private const val NOTIFICATION_ID = 100
    }

    @SuppressLint("ApplySharedPref")
    override fun onNewToken(s: String?) {
        super.onNewToken(s)
        try {
            // Log.i(TAG, "FCM token " + FirebaseInstanceId.getInstance().instanceId.result.token)
            val pref = baseContext.getSharedPreferences(TAG, Context.MODE_PRIVATE)
            pref.edit().putString(SP_FIREBASE_TOKEN, s).commit()
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        super.onMessageReceived(remoteMessage)
        Log.i("liu1110", "receive data " + remoteMessage?.data.toString())
        Log.i("liu1110", "receive data " + remoteMessage?.notification!!.title)
        Log.i("liu1110", "receive data " + remoteMessage?.notification!!.body)
        if (remoteMessage != null && remoteMessage.notification != null) {
            Log.i("liu1111", "receive notification " + remoteMessage.notification!!.title)
            Log.i("liu1111", "receive notification " + remoteMessage.notification!!.body)
            val builder = NotificationCompat.Builder(this)
            builder.setContentTitle(remoteMessage.notification!!.title)
            builder.setContentText(remoteMessage.notification!!.body)
            builder.setSmallIcon(R.mipmap.ic_launcher)
            builder.setWhen(System.currentTimeMillis())
            builder.setTicker(remoteMessage.notification!!.title!!)
            builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            builder.setAutoCancel(true)
            val intent = Intent(this, SplashActivity::class.java)
            builder.setContentIntent(PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT)) //requestCode 不能为0 否则MainActivity 将重建
            NotificationManagerCompat.from(this).notify(TAG, NOTIFICATION_ID, builder.build())
        } else if (!TextUtils.isEmpty(remoteMessage?.data.toString())) {
            val content = remoteMessage?.data.toString()
            val data = remoteMessage?.data
            val title = data?.get("title")
            var timeStamp = 0L
            try {
                timeStamp = java.lang.Long.valueOf(content)
            } catch (ex: Exception) {
                ex.printStackTrace()
                timeStamp = System.currentTimeMillis()
            }
            val recordTimeStamp = XLeoSp.getInstance(this).getLong(FieldParams.MESSAGE_NUMBER)
            if (timeStamp > recordTimeStamp) {
                XLeoToast.showMessage("收到红点消息")
                this.sendBroadcast(Intent(FieldParams.BroadcastAction.NEW_MESSAGE))
                XLeoSp.getInstance(this).putBoolean(FieldParams.PageStatus.HAS_NEW_MESSAGE, true)
            }

            val builder = NotificationCompat.Builder(this)
            builder.setContentTitle(title)
            builder.setContentText(title)
            builder.setSmallIcon(R.mipmap.ic_launcher)
            builder.setWhen(System.currentTimeMillis())
            builder.setTicker(title)
            builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            builder.setAutoCancel(true)
            val intent = Intent(this, SplashActivity::class.java)
            builder.setContentIntent(PendingIntent.getActivity(this, NOTIFICATION_ID + 100, intent, PendingIntent.FLAG_UPDATE_CURRENT)) //requestCode 不能为0 否则MainActivity 将重建
            NotificationManagerCompat.from(this).notify(TAG, NOTIFICATION_ID + 100, builder.build())

            Log.i("liu1112", "onMessage, messageId: ${remoteMessage?.getMessageId()} content $content")
        }
    }

    override fun onDeletedMessages() {
        super.onDeletedMessages()
        Log.i(TAG, "onDeletedMessages")
    }


}